#!/usr/bin/env python3
"""
Cross-platform build script for Ollama Translator
Builds executables for macOS, Windows, and Linux
"""

import os
import sys
import platform
import subprocess
import shutil
from pathlib import Path


def get_platform_info():
    """Get detailed platform information"""
    info = {
        'system': platform.system(),
        'release': platform.release(),
        'version': platform.version(),
        'machine': platform.machine(),
        'processor': platform.processor(),
        'python_version': platform.python_version(),
        'architecture': platform.architecture()[0]
    }
    return info


def check_dependencies():
    """Check if required dependencies are installed"""
    required_packages = ['PyInstaller', 'requests', 'PyQt6']
    
    print("Checking dependencies...")
    all_installed = True
    
    for package in required_packages:
        try:
            __import__(package.lower().replace('-', '_'))
            print(f"✓ {package}")
        except ImportError:
            print(f"✗ {package} not found")
            all_installed = False
    
    return all_installed


def install_dependencies():
    """Install missing dependencies"""
    print("Installing dependencies...")
    packages = ['PyInstaller', 'requests', 'PyQt6']
    
    for package in packages:
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install", package])
            print(f"✓ Installed {package}")
        except subprocess.CalledProcessError:
            print(f"✗ Failed to install {package}")
            return False
    
    return True


def create_build_directories():
    """Create build directory structure for all platforms"""
    platforms = ['macos', 'windows', 'linux']
    
    for platform_name in platforms:
        build_dir = Path(f"build_{platform_name}")
        dist_dir = Path(f"dist_{platform_name}")
        
        # Clean previous builds
        if build_dir.exists():
            shutil.rmtree(build_dir)
        if dist_dir.exists():
            shutil.rmtree(dist_dir)
        
        build_dir.mkdir(exist_ok=True)
        dist_dir.mkdir(exist_ok=True)
        print(f"✓ Created directories for {platform_name}")


def get_pyinstaller_args(target_platform):
    """Get PyInstaller arguments for specific platform"""
    base_args = [
        "--onefile",
        "--noconsole",
        "--name", "ollama_translate",
        "--add-data", "README.md:.",
        "--hidden-import", "config_manager",
        "--hidden-import", "ollama_client",
        "--hidden-import", "translator_gui",
        "--hidden-import", "config_window",
        "--hidden-import", "settings_dialog",
    ]
    
    if target_platform == 'windows':
        base_args.extend(["--icon", "NONE"])  # Placeholder for Windows icon
    elif target_platform == 'darwin':
        base_args.extend(["--osx-bundle-identifier", "com.ollama.translator"])
    
    return base_args


def build_for_platform(target_platform):
    """Build executable for specific platform"""
    print(f"\nBuilding for {target_platform}...")
    
    # Set platform-specific environment
    env = os.environ.copy()
    
    if target_platform == 'linux':
        # Set Qt platform to xcb for Linux
        env['QT_QPA_PLATFORM'] = 'xcb'
    
    # Build command
    cmd = [sys.executable, "-m", "PyInstaller"]
    cmd.extend(get_pyinstaller_args(target_platform))
    cmd.append("main.py")
    
    # Set workpath and distpath for platform-specific builds
    workpath = f"build_{target_platform}"
    distpath = f"dist_{target_platform}"
    
    cmd.extend(["--workpath", workpath])
    cmd.extend(["--distpath", distpath])
    
    try:
        print(f"Running: {' '.join(cmd)}")
        result = subprocess.run(cmd, check=True, env=env, capture_output=True, text=True)
        print(f"✓ Build for {target_platform} completed successfully")
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ Build for {target_platform} failed")
        if e.stderr:
            print(f"Error: {e.stderr}")
        return False


def build_with_spec():
    """Build using the spec file"""
    print("\nBuilding with spec file...")
    
    try:
        cmd = [sys.executable, "-m", "PyInstaller", "ollama_translate.spec", "--clean"]
        result = subprocess.run(cmd, check=True, capture_output=True, text=True)
        print("✓ Build with spec file completed successfully")
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ Build with spec file failed: {e}")
        if e.stderr:
            print(f"Error: {e.stderr}")
        return False


def create_platform_packages():
    """Create platform-specific packages and installers"""
    print("\nCreating platform packages...")
    
    # Create macOS app bundle structure
    if Path("dist/ollama_translate").exists():
        # macOS .app bundle
        if sys.platform == 'darwin':
            create_macos_app_bundle()
        
        # Windows installer script
        create_windows_installer()
        
        # Linux package script
        create_linux_package()


def create_macos_app_bundle():
    """Create macOS .app bundle"""
    print("Creating macOS .app bundle...")
    
    app_bundle = Path("dist/Ollama Translator.app")
    if app_bundle.exists():
        shutil.rmtree(app_bundle)
    
    # Create app bundle structure
    app_bundle.mkdir()
    contents_dir = app_bundle / "Contents"
    contents_dir.mkdir()
    macos_dir = contents_dir / "MacOS"
    macos_dir.mkdir()
    resources_dir = contents_dir / "Resources"
    resources_dir.mkdir()
    
    # Copy executable
    shutil.copy("dist/ollama_translate", macos_dir / "Ollama Translator")
    
    # Create Info.plist
    info_plist = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleExecutable</key>
    <string>Ollama Translator</string>
    <key>CFBundleIdentifier</key>
    <string>com.ollama.translator</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>Ollama Translator</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0.0</string>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>LSMinimumSystemVersion</key>
    <string>10.13</string>
</dict>
</plist>"""
    
    with open(contents_dir / "Info.plist", "w") as f:
        f.write(info_plist)
    
    print("✓ macOS .app bundle created")


def create_windows_installer():
    """Create Windows installer script"""
    installer_script = """@echo off
REM Windows Installer Script for Ollama Translator

echo Installing Ollama Translator...

REM Check if Ollama service is running
tasklist | findstr ollama >nul
if errorlevel 1 (
    echo Warning: Ollama service is not running
    echo Please start Ollama before using the translator
)

REM Copy to Program Files if running as admin
if exist "%ProgramFiles%" (
    copy "dist\\ollama_translate.exe" "%ProgramFiles%\\Ollama Translator\\"
    echo Installed to %%ProgramFiles%%\\Ollama Translator
    echo.
    echo You can create a desktop shortcut by:
    echo 1. Right-click on desktop
    echo 2. Select New -> Shortcut
    echo 3. Enter "%%ProgramFiles%%\\Ollama Translator\\ollama_translate.exe"
) else (
    echo Cannot install to Program Files (admin rights required)
    echo You can run the executable directly from: dist\\ollama_translate.exe
)

echo Installation complete!
echo.
echo To run the application:
echo   dist\\ollama_translate.exe
pause
"""
    
    with open("install_windows.bat", "w") as f:
        f.write(installer_script)
    
    print("✓ Windows installer script created")


def create_linux_package():
    """Create Linux package script"""
    installer_script = """#!/bin/bash
# Linux Installation Script for Ollama Translator

echo "Installing Ollama Translator..."

# Check if Ollama is running
if ! pgrep -x "ollama" > /dev/null; then
    echo "Warning: Ollama service is not running"
    echo "Please start Ollama with: systemctl --user start ollama"
fi

# Create desktop entry
desktop_entry="""[Desktop Entry]
Version=1.0
Type=Application
Name=Ollama Translator
Comment=Translate text using local Ollama service
Exec=/usr/local/bin/ollama_translate
Icon=ollama-translator
Categories=Utility;Translation;
Terminal=false
"""

# Copy executable to system locations
if [ -w /usr/local/bin ]; then
    sudo cp dist/ollama_translate /usr/local/bin/
    echo "Installed to /usr/local/bin/ollama_translate"
    
    # Create desktop entry
    echo "$desktop_entry" | sudo tee /usr/share/applications/ollama-translator.desktop > /dev/null
    echo "Desktop entry created"
else
    echo "Cannot install to system locations (permission denied)"
    echo "You can run the executable directly from: dist/ollama_translate"
fi

echo "Installation complete!"
echo "Run with: ollama_translate"
"""
    
    with open("install_linux.sh", "w") as f:
        f.write(installer_script)
    
    os.chmod("install_linux.sh", 0o755)
    print("✓ Linux installer script created")


def verify_builds():
    """Verify all builds were successful"""
    print("\nVerifying builds...")
    
    builds = {
        'default': Path("dist/ollama_translate"),
        'macos': Path("dist_macos/ollama_translate"),
        'windows': Path("dist_windows/ollama_translate.exe"),
        'linux': Path("dist_linux/ollama_translate")
    }
    
    all_good = True
    for platform_name, executable_path in builds.items():
        if executable_path.exists():
            size = executable_path.stat().st_size / (1024*1024)
            print(f"✓ {platform_name}: {executable_path} ({size:.1f} MB)")
            
            # Make executable on Unix-like systems
            if platform_name in ['default', 'macos', 'linux']:
                os.chmod(executable_path, 0o755)
        else:
            print(f"✗ {platform_name}: Build not found")
            all_good = False
    
    return all_good


def main():
    """Main build function"""
    print("=" * 60)
    print("Ollama Translator - Cross-Platform Build Script")
    print("=" * 60)
    
    # Show platform info
    info = get_platform_info()
    print(f"Building on: {info['system']} {info['release']} ({info['architecture']})")
    print(f"Python: {info['python_version']}")
    
    # Check and install dependencies
    if not check_dependencies():
        print("\nInstalling missing dependencies...")
        if not install_dependencies():
            print("\nFailed to install dependencies. Please install manually:")
            print("pip install PyInstaller requests PyQt6")
            sys.exit(1)
    
    # Create build directories
    create_build_directories()
    
    # Build for current platform using spec file
    if not build_with_spec():
        print("\nFalling back to direct build...")
        
        # Build for current platform
        current_platform = {
            'darwin': 'macos',
            'win32': 'windows',
            'linux': 'linux'
        }.get(sys.platform, 'linux')
        
        if not build_for_platform(current_platform):
            print("\nBuild failed. Please check the errors above.")
            sys.exit(1)
    
    # Create platform packages
    create_platform_packages()
    
    # Verify builds
    if verify_builds():
        print("\n" + "=" * 60)
        print("BUILD SUCCESSFUL!")
        print("=" * 60)
        print("\nBuilt executables are available in:")
        print("  dist/ - Current platform build")
        print("  dist_macos/ - macOS build")
        print("  dist_windows/ - Windows build") 
        print("  dist_linux/ - Linux build")
        print("\nPlatform-specific installers created:")
        print("  install_windows.bat - Windows installer")
        print("  install_linux.sh - Linux installer")
        
        if sys.platform == 'darwin':
            print("  Ollama Translator.app - macOS application bundle")
        
        print("\nTo run the application:")
        print("  ./dist/ollama_translate")
    else:
        print("\nSome builds failed. Check the errors above.")
        sys.exit(1)


if __name__ == "__main__":
    main()